package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否已经完成登录
 */
@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //匹配路径,支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/favicon.ico",
                "/user/login",
                "/user/logout",
                "/user/sendMsg",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        String requestURI = request.getRequestURI();
        log.info("拦截到 " + requestURI + " 请求!");
        if (urlCheck(requestURI, urls)) {
            filterChain.doFilter(request, response);
            log.info("已放行 " + requestURI + " 请求!");
            return;
        }
        //判断session是否存在
        Long employeeId = (Long) request.getSession().getAttribute("employee");
        Long userId = (Long) request.getSession().getAttribute("user");
        if (employeeId != null) {
            //获取登录用户id,保存到线程的副本中(线程域) 先保存在放行不然还没保存它就去获取了
            BaseContext.setCurrendId(employeeId);
            filterChain.doFilter(request, response);
            //long id2 = Thread.currentThread().getId();
            //log.info("线程id:{}",id2);
            log.info("成功登录");
            return;
        }
        if (userId != null) {
            //获取登录用户id,保存到线程的副本中(线程域) 先保存在放行不然还没保存它就去获取了
            BaseContext.setCurrendId(userId);
            filterChain.doFilter(request, response);
            log.info("成功登录");
            return;
        }
        log.info("没有session " + requestURI + " 跳转登录页面");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    /**
     * 匹配url
     *
     * @param uri
     * @param urls
     * @return
     */
    public boolean urlCheck(String uri, String[] urls) {
        for (String url : urls) {
            //参数顺序不能换,有通配符的在前面
            if (PATH_MATCHER.match(url, uri)) {
                return true;
            }
        }
        return false;
    }
}
